package com.vdongchina.thread.base;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * 第5课:线程管道
 * piped 管道流 ,多线程间的交互
 * 管道输入输出流主要用于线程间的数据传输
 * pipedOutputStream,pipedInputStream 字节流
 * pipedReader,pipedWriter 字符流
 */
public class ThreadPipedDemo {


    public static void main(String[] args) throws IOException {

        PipedReader in = new PipedReader();
        PipedWriter out = new PipedWriter();
        out.connect(in);
        Thread reader = new Thread(new Reader(in), "printThread");
        reader.start();
        try {
            int receive = 0;
            while ((receive = System.in.read()) != -1) {
                out.write(receive);
            }
        } finally {
            out.close();
        }


    }
    static class Reader implements Runnable {
        private PipedReader in;
        public Reader(PipedReader in) {
            this.in = in;
        }
        @Override
        public void run() {
            int receive = 0;
            try {
                while ((receive = in.read()) != -1) {
                    System.out.print((char) receive);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
